<?php

namespace app\admin\controller\wanlshop;

use app\admin\model\wanlshop\Pay;
use app\api\model\wanlshop\OrderGift;
use app\common\controller\Backend;
use think\Db;
use app\admin\model\wanlshop\OrderGoods;

/**
 * 订单管理
 *
 * @icon fa fa-circle-o
 */
class Order extends Backend
{

    /**
     * Order模型对象
     * @var \app\admin\model\wanlshop\Order
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\wanlshop\Order;
        $this->view->assign("stateList", $this->model->getStateList());
        $this->view->assign("statusList", $this->model->getStatusList());
    }

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->with(['user', 'shop', 'ordergoods', 'pay'])
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->with(['user', 'shop', 'ordergoods' => function ($query) {
                    $query->where('type', 'new');
                }, 'pay'])
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            foreach ($list as $row) {
                $row->getRelation('user')->visible(['username', 'nickname']);
                $row->getRelation('shop')->visible(['shopname']);
                /*$row->pay = model('app\admin\model\wanlshop\Pay')
                    ->where(['order_id' => $row['id'], 'type' => 'goods'])
                    ->field('pay_no, price, order_price, freight_price, discount_price, actual_payment')
                    ->find();*/
                $row->order_type_text = \app\admin\model\wanlshop\Order::getOrderType($row->id);
                if ($row->state == 5 || $row->state == 10) {
                    $text = (new \app\admin\model\wanlshop\Refund())->getRefundStateText($row->id, $row->user_id);
                    $row->refund_state_text = $text;
                } else {
                    $row->refund_state_text = '';
                }
            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 详情
     */
    public function detail($id = null)
    {
        $row = $this->model->with(['pay'])->where('id', $id)->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($row['state'] == 5 || $row['state'] == 10) {
            $row['refund_state_text'] = (new \app\admin\model\wanlshop\Refund())->getRefundStateText($row->id, $row->user_id);
        } else {
            $row['refund_state_text'] = '';
        }
        $row['ordergoods'] = OrderGoods::where(['order_id' => $id, 'type' => 'new'])->select();
        $row['images'] = $row['images'] ? explode(',', $row['images']) : [];

        $row['address'] = model('app\api\model\wanlshop\OrderAddress')
            ->where(['order_id' => $id])
            ->order('isaddress desc')
            ->field('id,name,mobile,address,address_name')
            ->find();
        $row['s_name'] = '';
        if ($row['real_store_id']) {
            $row['s_name'] = \app\admin\model\wanlshop\Shop::where('id', $row['real_store_id'])->value('shopname');
        }

        // 查询快递状态
        switch ($row['state']) {
            case 1:
                $express = [
                    'context' => '付款后，即可将宝贝发出',
                    'status' => '尚未付款',
                    'time' => date('Y-m-d H:i:s', $row['createtime'])
                ];
                break;
            case 2:
                $express = [
                    'context' => '商家正在处理订单',
                    'status' => '已付款',
                    'time' => date('Y-m-d H:i:s', $row['paymenttime'])
                ];
                break;
            default: // 获取物流
                $eData = model('app\api\model\wanlshop\KuaidiSub')
                    ->where(['express_no' => $row['express_no']])
                    ->find();
                // 获取数据 兼容PHP7.4	1.1.5升级
                if (!empty($eData['data'])) {
                    $ybData = json_decode($eData['data'], true);
                    // 运单状态 1.0.6升级
                    $statusText = ['在途', '揽收', '疑难', '签收', '退签', '派件', '退回', '转投'];
                    $status = $statusText[0];
                    if (in_array('status', $ybData[0])) {
                        $status = $ybData[0]['status'];
                    } else {
                        if ($eData['ischeck'] === 1) {
                            $status = $statusText[3];
                        } else {
                            $status = $statusText[$eData['state']];
                        }
                    }
                    $express = [
                        'status' => $status,
                        'context' => $ybData[0]['context'],
                        'time' => $ybData[0]['time'],
                    ];
                } else {
                    $express = [
                        'status' => '已发货',
                        'context' => '包裹正在等待快递小哥揽收~',
                        'time' => date('Y-m-d H:i:s', $row['delivertime'])
                    ];
                }
        }
        $this->view->assign("kuaidi", $express);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 快递查询
     */
    public function relative_old($id = null)
    {
        $row = $this->model->get($id);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $data = model('app\api\model\wanlshop\KuaidiSub')
            ->where(['express_no' => $row['express_no']])
            ->find();
        $list = [];
        $week = array(
            "0" => "星期日",
            "1" => "星期一",
            "2" => "星期二",
            "3" => "星期三",
            "4" => "星期四",
            "5" => "星期五",
            "6" => "星期六"
        );
        if ($data) {
            // 兼容PHP7.4	1.1.5升级
            $data = json_decode($data['data'], true);
            foreach ($data as $vo) {
                $list[] = [
                    'time' => strtotime($vo['time']),
                    'status' => in_array('status', $vo) ? $vo['status'] : '在途',  // 1.0.6升级
                    'context' => $vo['context'],
                    'week' => $week[date('w', strtotime($vo['time']))]
                ];
            }
        }
        $this->view->assign("week", $week);
        $this->view->assign("list", $list);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    public function relative($id = null)
    {
        $row = $this->model->get($id);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        // $data = model('app\api\model\wanlshop\KuaidiSub')
        // 	->where(['express_no' => $row['express_no']])
        // 	->find();

        $expModle = new \addons\expressquery\library\Expressquery();
        $data = $expModle->getExpressList($row['express_name'], $row['express_no']);
        if (isset($data['code']) && $data['code'] == 0) {
            $this->error($data['msg']);
        }

        $list = [];
        $week = array(
            "0" => "星期日",
            "1" => "星期一",
            "2" => "星期二",
            "3" => "星期三",
            "4" => "星期四",
            "5" => "星期五",
            "6" => "星期六"
        );
        if ($data) {
            // 兼容PHP7.4	1.1.5升级
            // $data = json_decode($data['data'], true);
            $data = $data['data'];
            foreach ($data as $vo) {
                $list[] = [
                    'time' => strtotime($vo['time']),
                    'status' => in_array('status', $vo) ? $vo['status'] : '在途',  // 1.0.6升级
                    'context' => $vo['step'],
                    'week' => $week[date('w', strtotime($vo['time']))]
                ];
            }
        }
        $this->view->assign("week", $week);
        $this->view->assign("list", $list);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     *  回购记录
     */
    public function buyback()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        // 模型
        $this->model = new OrderGoods();

        $oid = $this->request->param('oid');
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $oid = $this->request->param('oid');
            $total = $this->model
                ->where($where)
                ->where(["order_id" => $oid, 'type' => 'old'])
                ->count();

            $list = $this->model
                ->with(['user' => function ($query) {
                    $query->withField('id,username');
                }, 'goods' => function ($query) {
                    $query->withField('id, title, image, price');
                }])
                ->where($where)
                ->where(["order_id" => $oid, 'type' => 'old'])
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        // 获取到父页面的订单id 回传给自己
        $this->assignconfig('oid', $oid);
        return $this->view->fetch();
    }

    //废弃,用batchaudit审核
    public function edit($ids = null, $except = false)
    {
        $row = $this->model->get($ids);
        $pay = Pay::where('order_id', $ids)->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $this->view->assign("images", array_filter(explode(',', $row['images'])));
        $this->view->assign("price", $pay->price);
        $this->view->assign("row", $row);
        $this->view->assign("state", $row->state);
        if ($this->request->isPost()) {
            $params = $this->request->post();
            if (!in_array($row['state'], [8, 9])) {
                $this->success('操作成功');
            }
            if ($params['price'] > $pay->price) {
                $this->error('价格不能高于订单总价');
            }

//            if ($row['pay']['order_price'] != $params['price']) {
            Db::transaction(function () use ($pay, $params, $row) {
                //更新支付数据
                $sub = bcsub($pay->price, $params['price'], 2);
                $pay->price = $params['price'];
                $pay->system_price = bcadd($pay->system_price, $sub);
                $pay->save();

                //更新订单
                $row->state = $params['state'] == 1 ? 1 : 9;
                $row->save();
            });
//            }
            $this->success('操作成功');
        }
        return $this->view->fetch();
    }

    public function batchaudit($ids = null)
    {
        $data = $this->model->with(['ordergoods' => function ($query) {
            $query->withField('id,name,image');
        }, 'pay'])->where('id', 'in', explode(',', $ids))->select();

        if (!$data) {
            $this->error(__('No Results were found'));
        }
        foreach ($data as $item) {
            $item->images = $item->images ? explode(',', $item->images) : '';
            $item->order_type_text = $this->model::getOrderType($item['id']);
        }

        $this->view->assign("lists", $data);
        if ($this->request->isPost()) {
            $params = $this->request->post();
            Db::startTrans();
            foreach ($params['order_id'] as $key => $order_id) {
                $model = \app\admin\model\wanlshop\Order::find($order_id);
                $pay = Pay::where('order_id', $order_id)->find();
                if ($params['price'][$key] > $model->pay->price) {
                    $this->error('价格不能高于订单总价');
                }
                if (!in_array($model->state, [8, 9])) {
                    $this->success('操作成功');
                }

                //更新支付数据
                $sub = bcsub($pay->price, $params['price'][$key], 2);
                $pay->price = $params['price'][$key];
                $pay->system_price = bcadd($pay->system_price, $sub);
                $pay->save();

                //更新订单
                $model->state = $params['state'] == 1 ? 1 : 9;
                $model->reject_reason = $params['state'] == 1 ? '' : $params['reject_reason'];
                $model->save();
                Db::commit();
            }
            $this->success('操作成功');
        }
        return $this->view->fetch();
    }
}
